package com.lanp.springsd.config.aspect;

import com.lanp.springsd.common.RoutingWith;
import com.lanp.springsd.config.database.RoutingDataSourceContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;

/**
 * @author jiangpeng
 * Created with IntelliJ IDEA.
 * Description:  动态数据源aop设置
 * Date: 2022-03-07 10:47:05
 */
//@Aspect
//@Component
public class RoutingAspect {

    public RoutingAspect() {
        System.out.println("init RoutingAspect");
    }

    @Value("${pay.a:未配置}")
    private String a;


    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }


    /**
     * 以自定义 @openLog 注解为切点
     */
    @Pointcut("@annotation(com.lanp.springsd.common.RoutingWith)")
    public void RoutingWith() {
    }

    @Pointcut("execution(* com.lanp.springsd.controller.*.*(..))")
    public void getControllerApi() {

    }


    @Around("getControllerApi()")
    public Object routingWithDataSource(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RoutingWith routingWith = signature.getMethod().getAnnotation(RoutingWith.class);
        if (routingWith != null) {
            String key = routingWith.value();
            try (RoutingDataSourceContext ctx = new RoutingDataSourceContext(key)) {
                return joinPoint.proceed();
            }
        }
        return joinPoint.proceed();
    }

}
